var areaAll = function (options) {
    var defaults = {
        startFun: null,
        url: "/area/queryByPid",
        startIndex: 0,
        totalSelect: 5,
        DivId: "area_div",
        pid: 0,
        selectWidthArr: ["80px", "110px", "80px", "110px", "110px"],
        areaArr: ["省份:", " 市:", "  区县: ", "  街道: ", "  街道: "],
        idArr: ["province_id", "city_id", "district_id", "town_id", "town_id"],
        isNeedName: false,
        nameArr: ["province_name", "city_name", "district", "town", "town"],
        spaceArrLeft: [1, 1, 1, 1, 1],
        spaceArrRight: [1, 1, 1, 1, 1],
        data: null,
        backFun: null,
        name: "name"
    };

    var opt = $.extend(defaults, options);
    var fullDiv = $("#" + opt.DivId);
    fullDiv.html("");

    for (var i = 0; i < opt.startIndex; i++) {
        opt.areaArr[i] = "";
    }

    opt.totalSelect = (parseInt(opt.totalSelect) + parseInt(opt.startIndex));


    if (opt.totalSelect > 5) {
        opt.totalSelect = 5;
    }
    if (fullDiv.find("select").length == 0) {
        for (var i = 0; i < opt.totalSelect; i++) {
            var select = '<select class="form-control" name=' + opt.idArr[i] + ' style="width:' + opt.selectWidthArr[i] + ';display:inline-block" data-val="' + (eval("opt.data==undefined|| opt.data==null?'': opt.data." + opt.idArr[i]) || "") + '"></select>';
            var hiddenInput = "";
            if (opt.isNeedName) {
                hiddenInput = '<input type="hidden" name="' + opt.nameArr[i] + '"/>'
            }
            fullDiv.append(outSpace(opt.spaceArrLeft[i]) + opt.areaArr[i] + outSpace(opt.spaceArrRight[i]) + select + hiddenInput);
        }
    }


    for (var i = 0; i < opt.startIndex; i++) {
        fullDiv.children().eq(i).css({"display": "none"});
    }

    $.fn.fullSelect(opt, fullDiv, true, 0);
    $.fn.areaClick(opt);
};

$.fn.fullSelect = function (opt, fullDiv, flag, indexSelect) {
    if (flag) {
        indexSelect = 0;
    }

    if (opt.totalSelect == indexSelect) {
        return false;
    }
    $.ajax({
        type: "post",
        dataType: "json",
        data: {pid: opt.pid, type: indexSelect},
        url: opt.url,
        success: function (data) {
            if (data.code == 404) {
                if (opt.backFun)
                    opt.backFun(fullDiv);
                return;
            }
            var $select = fullDiv.find("select:eq(" + indexSelect + ")")[0];
            $.each(data.data, function (index, item) {
                if (index == 0) {
                    $($select).append('<option value="">请选择</option>');
                }
                $($select).append('<option data-area-code=' + item.code + ' value=' + item.id + ' ' + ($($select).attr("data-val") == item.code ? "selected=selected" : "") + '>' + item[opt.name] + '</option>');
            });
            $($select).next().val($($select).find("option[selected='selected']").text());
            if (indexSelect < opt.totalSelect) {
                flag = false;
                indexSelect++;
                var selectedVal = $($select).find('option:selected').val();
                opt.pid = selectedVal == undefined || selectedVal == "" ? "" : selectedVal;
                if (opt.pid == "") {
                    indexSelect = indexSelect - 2;
                    if (indexSelect == -1) {
                        indexSelect = 0;
                    }
                    var selectArr = fullDiv.find("select:gt(" + indexSelect + ")");

                    $.each(selectArr, function (index, item) {
                        $(item).append('<option value="">请选择</option>');
                    })
                } else {
                    $.fn.fullSelect(opt, fullDiv, flag, indexSelect);
                }
            }
            if (opt.backFun)
                opt.backFun(fullDiv);

        }
    })
};


$.fn.areaClick = function (opt) {
    var $div = $("#" + opt.DivId);

    $div.on("change", "select", function () {
        if (opt.startFun)
            opt.startFun($div);
        if (opt.isNeedName) {
            opt.totalSelect = opt.totalSelect * 2;
        }

        var index = $(this).index();
        if (index == (opt.totalSelect - 1)) {
            $div.attr("data-area-position-id", $(this).find("option:selected").val());
            $(this).attr("data-selected-area-code", $(this).find("option:selected").attr("data-area-code"));
            return;
        }

        var val = $(this).val();
        if (val == "") {
            $(this).removeAttr("data-selected-area-code");
            $.fn.areaClickBlank($(this), opt, index);
            return;
        } else {
            $div.attr("data-area-position-id", val);
            $(this).attr("data-selected-area-code", $(this).find("option:selected").attr("data-area-code"));
        }
        if (opt.isNeedName) {
            $(this).next().val($(this).find("option:selected").text());
            $.fn.nextSelectShow($(this).next().next(), opt, index);
        } else {
            $.fn.nextSelectShow($(this).next(), opt, index);
        }

    })
};

$.fn.nextSelectShow = function (nextSelect, opt, _index) {
    if (++_index == (opt.totalSelect)) {
        return;
    }
    var pid = "";
    if (opt.isNeedName) {
        pid = nextSelect.prev().prev().val();
    } else {
        pid = nextSelect.prev().val();
    }
    if (nextSelect != undefined) {
        nextSelect.removeAttr("data-selected-area-code");
        $.ajax({
            type: "post",
            dataType: "json",
            data: {pid: pid, type: _index},
            url: opt.url,
            success: function (data) {
                var html = "";
                if (data.code == 404) {
                    return;
                }
                $.each(data.data, function (index, item) {
                    if (index == 0) {
                        html += ('<option value="" selected=selected>请选择</option>');
                    }
                    html += '<option data-area-code=' + item.code + ' value=' + item.id + '>' + item[opt.name] + '</option>';
                });
                nextSelect.html(html);
                if (opt.isNeedName) {
                    $(nextSelect).next().val("");
                }
                var selectArr = $("#" + opt.DivId).find("select:gt(" + _index + ")");
                $.each(selectArr, function (index, item) {
                    $(item).html('<option value="">请选择</option>');
                    if (opt.isNeedName) {
                        $(item).next().val("");
                    }
                })
            }
        })
    }
};


$.fn.areaClickBlank = function (clickSelect, opt, index) {
    if (++index == (opt.totalSelect)) {
        return;
    }
    var html = '<option value="" selected=selected>请选择</option>';
    if (opt.isNeedName) {
        if ($(clickSelect).next().next() != undefined) {
            $(clickSelect).next().next().html(html);
            $.fn.areaClickBlank($(clickSelect).next().next(), opt, index);
        }
        $(clickSelect).next().val("");
    } else {
        var $next = $(clickSelect).next();
        $next.removeAttr("data-selected-area-code");
        if ($next != undefined) {
            $next.html(html);
            $.fn.areaClickBlank($(clickSelect).next(), opt, index);
        }
    }
};

function outSpace(number) {
    var spaceTotal = "";
    for (var i = 0; i < number; i++) {
        spaceTotal += "&nbsp;"
    }
    return spaceTotal;
}
